from app import db
from werkzeug.security import generate_password_hash, check_password_hash

class User(db.Model):
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True)  # 保留id作为主键，方便数据操作
    username = db.Column(db.String(50), unique=True, nullable=False) # 用户名
    password_hash = db.Column(db.String(128), nullable=False)  # 存储加密后的密码
    created_at = db.Column(db.DateTime, default=db.func.current_timestamp())

    def set_password(self, password):
        """加密存储密码"""
        self.password_hash = generate_password_hash(
            password,
            method='pbkdf2:sha256',
            salt_length=16
        )

    def check_password(self, password):
        """验证密码"""
        return check_password_hash(self.password_hash, password)
        
    def to_dict(self):
        """转换为字典，方便接口返回"""
        return {
            'id': self.id,
            'username': self.username,
            'created_at': self.created_at.isoformat()
        }
